import React, { Suspense, useState, useEffect } from "react";
import {
  Routes,
  Route,
  useNavigate,
  useLocation,
  useParams,
  useSearchParams,
} from "react-router-dom";
import routes from "./routes";
import { Mask, DotLoading, Toast } from "antd-mobile";
import store from "../store";
import action from "../store/action";

// 统一路由配置
const isCheckLogin = (path) => {
  let {
    base: { info },
  } = store.getState();
  const checkList = ["/personal", "/store", "/update"];
  return !info && checkList.includes(path);
};
const Element = function Element(props) {
  let { component: Component, meta, path } = props;
  let isShow = !isCheckLogin(path);
  let [_, setRandom] = useState(0);

  useEffect(() => {
    if (isShow) return;
    (async () => {
      // 如果info值不存在
      let infoAction = await action.base.queryUserInfoAsync();
      let info = infoAction.info;
      if (!info) {
        // 跳转到登陆页面
        Toast.show({
          icon: "fail",
          content: "请先登录",
        });
        navigate({
          pathname: "/login",
          search: `?to=${path}`,
        });
        return;
      }
      store.dispatch(infoAction);
      setRandom(+new Date());
    })();
  });

  const navigate = useNavigate();
  const location = useLocation();
  const params = useParams();
  const [usp] = useSearchParams();
  // 修改页面的TITLE
  let { title = "知乎日报-WebApp" } = meta || {};
  document.title = title;

  return (
    <>
      {isShow ? (
        <Component
          navigate={navigate}
          location={location}
          params={params}
          usp={usp}
        />
      ) : (
        <Mask visible={true}>
          <DotLoading color="white" />
        </Mask>
      )}
    </>
  );
};

export default function RouterView() {
  return (
    <Suspense
      fallback={
        <Mask visible={true}>
          <DotLoading color="white" />
        </Mask>
      }
    >
      <Routes>
        {routes.map((item) => {
          let { name, path } = item;
          return (
            <Route key={name} path={path} element={<Element {...item} />} />
          );
        })}
      </Routes>
    </Suspense>
  );
}
